import math
import time
import os
import transpositionEncrypt
import sys


def main(inputFileName, outputFileName, model='encrypt', myKey = 10):
    # inputFileName = "frankenstein.txt"
    # outputFileName = "frankenstein.encrypted.txt"
    # myKey = 10
    # outputFileName = "frankenstein.txt2"
    # inputFileName = "frankenstein.encrypted.txt"
    # myKey = 10

    if not os.path.exists(inputFileName):
        print(f"The file {inputFileName} is not exists. quitting...")
        sys.exit()
    else:
        print("prepare to read the file:", inputFileName)

    if os.path.exists(outputFileName):
        print(f"This will overwrite the file:{outputFileName}, (C)ontinue or (Q)uit?")
        response = input(">")
        if not response.lower().startswith('c'):
            sys.exit()

    fileObj = open(inputFileName)
    content = fileObj.read()
    fileObj.close()
    print(f"read content length:{len(content)}")

    startTime = time.time()
    if model.lower() == 'encrypt':
        pass
    else:
        # 解密需要重新计算密钥
        myKey = math.ceil(len(content) / myKey)

    translated = transpositionEncrypt.encrypt(content, myKey)
    totalTime = round(time.time() - startTime, 2)
    print(f"cost time:{totalTime}")

    outputFileObj = open(outputFileName, 'w')
    outputFileObj.write(translated)
    outputFileObj.close()


if __name__ == '__main__':
    inputFileName = input("input file name:")
    outputFileName = input("out put file name:")
    model = input("(E)ncrypt or (D)encrypt?")
    if model.lower().startswith('e'):
        model = "encrypt"
    else:
        model = "dencrypt"

    main(inputFileName=inputFileName, outputFileName=outputFileName, model=model)
